import logging
import os
from logging.handlers import TimedRotatingFileHandler

class Logger:
    def __init__(self, name=__name__):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.INFO)

        formatter = logging.Formatter(
            '[%(asctime)s] - %(name)s - [%(levelname)s] - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S',
            style='%')

        # 添加中文日志级别名称映射
        # logging.addLevelName(logging.DEBUG, '调试')
        # logging.addLevelName(logging.INFO, '信息')
        # logging.addLevelName(logging.WARNING, '警告')
        # logging.addLevelName(logging.ERROR, '错误')
        # logging.addLevelName(logging.CRITICAL, '严重')

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)

        # 文件处理器（自动轮转）
        log_dir = os.path.join(os.path.dirname(__file__), '../logs')
        os.makedirs(log_dir, exist_ok=True)
        file_handler = TimedRotatingFileHandler(
            filename=os.path.join(log_dir, 'mcp.log'),
            when='midnight',
            interval=1,
            backupCount=7,
            encoding='utf-8'
        )
        file_handler.setFormatter(formatter)

        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)

    def get_logger(self):
        return self.logger

# 全局日志实例
logger = Logger().get_logger()